package com.chang.bootplus.config.security;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chang.bootplus.base.utils.ApiResponse;
import com.chang.bootplus.base.utils.BeanUtil;
import com.chang.bootplus.base.utils.JwtUtils;
import com.chang.bootplus.entity.School;
import com.chang.bootplus.service.SchoolService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {


	@Autowired
	SchoolService schoolService;


	@Autowired
	JwtUtils jwtUtils;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {


		response.setContentType("application/json;charset=UTF-8");
		ServletOutputStream outputStream = response.getOutputStream();
		// 生成jwt，并放置到请求头中
		String jwt = jwtUtils.generateToken(authentication.getName());
		response.setHeader(jwtUtils.getHeader(), jwt);
//		outputStream.write(JSONUtil.toJsonStr(new ApiResponse(BeanUtil.beanA2beanB(byUsername, UserInfoVO.class)).setReMsg("登录成功")).getBytes("UTF-8"));
		String name = authentication.getName();
		School one = schoolService.getOne(new LambdaQueryWrapper<School>().eq(School::getNickName, name));
		HashMap<String, Object> map = new HashMap<>();
		map.put("department",one.getDepartment());
		map.put("nickname",one.getNickName());
		map.put("logname",one.getLogName());
		map.put("schoolId",one.getId());
		map.put("schoolName",one.getSchoolName());
		outputStream.write(JSONUtil.toJsonStr(new ApiResponse<>().setBody(map).setReMsg("登录成功")).getBytes("UTF-8"));
		outputStream.flush();
		outputStream.close();
	}

}
